package store_fashion

import (
	"fmt"
	"jihe.common/protos/base_server/proto"
	"jihe.common/tool"
	"time"
)

func (s *Model) Create(in *proto.DStoreFashion) (ret *proto.DStoreFashion, err error) {
	ret = new(proto.DStoreFashion)
	ret.Id = fmt.Sprintf("%d", tool.GetSnowflakeId())
	sqlStr := fmt.Sprintf("INSERT INTO %s (id, d_uid, cover, name, need_id, price, idea, group_id)VALUES($1,$2,$3,$4,$5,$6,$7,$8)", s.Name)
	_, err = s.Db.Exec(sqlStr, ret.Id, in.DUid, in.Cover, in.Name, in.NeedId, in.Price, in.Idea, in.GroupId)
	if err != nil {
		return
	}
	return
}

func (s *Model) GetListByLimit(groupId string) (ret []*proto.DStoreFashion, err error) {
	sqlStr := fmt.Sprintf("select id, d_uid, cover, name, need_id, price, status, idea, group_id, created_at, updated_at from %s where group_id = $1 order by created_at desc limit 100", s.Name)
	rows, err := s.Db.Query(sqlStr, groupId)
	if err != nil {
		return
	}
	for rows.Next() {
		item := &proto.DStoreFashion{}
		var (
			createdTime *time.Time
			updatedTime *time.Time
		)
		err = rows.Scan(&item.Id, &item.DUid, &item.Cover, &item.Name, &item.NeedId, &item.Price, &item.Status, &item.Idea, &item.GroupId, &createdTime, &updatedTime)
		if err != nil {
			return
		}
		item.CreatedAt = createdTime.Format("2006-01-02 15:04:05")
		item.UpdatedAt = updatedTime.Format("2006-01-02 15:04:05")
		ret = append(ret, item)
	}
	return
}

func (s *Tx) Delete(worksCollectionId string) (err error) {
	sqlStr := fmt.Sprintf("DELETE FROM %s WHERE works_collection_id = $1", s.Name)
	_, err = s.Db.Exec(sqlStr, worksCollectionId)
	if err != nil {
		return
	}
	return
}

func (s *Model) GetByDuid(dUid string) (ret *proto.DStore, err error) {
	ret = new(proto.DStore)
	sqlStr := fmt.Sprintf("select id, name, description, d_uid, created_at, updated_at from %s where d_uid = $1", s.Name)
	var (
		createTime *time.Time
		updateTime *time.Time
	)
	err = s.Db.QueryRow(sqlStr, dUid).Scan(&ret.Id, &ret.Name, &ret.Description, &ret.DUid, &createTime, &updateTime)
	if err != nil {
		return
	}
	return
}
